<template>
  <div>
    <el-dialog
      v-loading.lock="loading"
      class="base-dialog"
      :custom-class="'panna-dialog_medium'"
      append-to-body
      title="模板信息"
      align="center"
      destroy-on-close
      :close-on-click-modal="false"
      :visible.sync="innerDialogFormVisible"
    >
      <!-- base-pipeline-layout  -->
      <el-form
        ref="formData"
        class="system-user-form"
        label-width="100px"
        :model="formData"
        :rules="formDataRules"
        status-icon
      >
        <el-form-item
          label="记录编号"
          :label-width="formLabelWidth"
          prop="templateCode"
          :error="errorMsg.templateCode"
        >
          <el-input
            v-model.trim="formData.templateCode"
            autocomplete="off"
            :disabled="readonly"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="模板名称"
          :label-width="formLabelWidth"
          prop="templateName"
          :error="errorMsg.templateName"
        >
          <el-input
            v-model="formData.templateName"
            autocomplete="off"
            :disabled="readonly"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="行业领域"
          :label-width="formLabelWidth"
          prop="industry"
          :error="errorMsg.industry"
        >
          <el-input
            v-model="formData.industry"
            autocomplete="off"
            :disabled="readonly"
          ></el-input>
        </el-form-item>
        <!-- <el-form-item
          label="样品类别"
          :label-width="formLabelWidth"
          :class="{ readonly: readonly }"
          prop="sampleCategoryName"
          :error="errorMsg.sampleCategoryName"
        >
          <el-select
            v-model="formData.sampleCategoryName"
            multiple
            :filterable="!readonly"
            allow-create
            default-first-option
            placeholder="请选择或者输入样品类别"
            @change="changeSampleCategoryName"
          >
            <el-option
              v-for="item in formData.experimentSampleCategorys"
              :key="item.id"
              :label="item.name"
              :value="item.name"
              :disabled="readonly"
            ></el-option>
          </el-select>
        </el-form-item> -->
        <!-- <el-form-item
          label="检测项目"
          :label-width="formLabelWidth"
          :class="{ readonly: readonly }"
          prop="detectionItemName"
          :error="errorMsg.detectionItemName"
        > -->
        <!-- <el-input v-model="formData.detectionItemName" autocomplete="off"></el-input> -->
        <!-- <el-select
            v-model="formData.detectionItemName"
            multiple
            :filterable="!readonly"
            allow-create
            default-first-option
            placeholder="请选择或者输入检测项目"
            @change="changeDetectionItemName"
          >
            <el-option
              v-for="item in formData.experimentDetectionItems"
              :key="item.id"
              :label="item.name"
              :value="item.name"
              :disabled="readonly"
            ></el-option>
          </el-select>
        </el-form-item> -->
        <el-form-item
          label="描述"
          :label-width="formLabelWidth"
          prop="description"
          :error="errorMsg.description"
        >
          <el-input
            v-model="formData.description"
            autocomplete="off"
            :disabled="readonly"
          ></el-input>
        </el-form-item>

        <el-form-item
          label="检测项目"
          :label-width="formLabelWidth"
          prop="description"
          :error="errorMsg.description"
        >
          <el-row>
            <el-col :span="4">
              <el-button
                type="primary"
                :disabled="readonly"
                @click="choiceDetectionItem"
                >选择检测项目</el-button
              ></el-col
            >
          </el-row>
          <el-row>
            <el-table
              ref="tableDetectionItem"
              :data="tableDetectionItem"
              border
              style="width: 100%"
            >
              <el-table-column prop="sampleTypeName" label="样品类别" />
              <el-table-column prop="name" label="检测项目" />
              <el-table-column
                prop="sysBusinessDetectionItemSonName"
                label="项目分项"
              />
            </el-table>
          </el-row>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer" align="center">
        <el-button
          v-if="!readonly"
          type="primary"
          @click="onSubmit('formData')"
          >保 存</el-button
        >
        <el-button @click="nextStep()">下一步</el-button>
      </div>
    </el-dialog>
    <ChoiceDetectionItemDialog
      ref="ChoiceDetectionItemDialog"
      v-model="dialogDetectionItem"
      :generate-button-state="false"
      :same-sample-category="false"
      @DetectionItemClose="detectionItemClose"
    />
    <ExperimentTemplateEditForm
      ref="ExperimentTemplateEditForm"
      :dialog-form-visible2.sync="dialogFormVisible2"
      :readonly="readonly"
      @sendTemplate="getTemplate"
    />
  </div>
</template>

<script>
import { create, update } from "../../../api/Eln/ExperimentTemplate.js";
import ExperimentTemplateEditForm from "./ExperimentTemplateEditForm.vue";
import { getSingleList } from "../../../api/Eln/ExperimentTemplate.js";
import { deepClone } from "../../../utils";
import _ from "lodash";
export default {
  name: "ExperimentTemplateEdit",
  components: { ExperimentTemplateEditForm },
  props: {
    dialogFormVisible: {
      type: Boolean,
      default: false,
    },
    readonly: {
      type: Boolean,
      default: false,
    },
    editId: {
      type: String,
      default: "",
    },
  },
  data() {
    return {
      loading: false,
      dialogDetectionItem: false,
      templateContentDto: "",
      innerDialogFormVisible: false,
      dialogFormVisible2: false,
      formLabelWidth: "100px",
      tableDetectionItem: [],
      tableDetectionItemAndSubentry: [],
      formData: {
        id: "",
        templateCode: "",
        templateName: "",
        industry: "",
        // sampleCategoryName: "",
        templateContentDto: "",
        experimentSampleCategorys: [],
        detectionItemName: "",
        experimentDetectionItems: [],
        tableDetectionItemAll: [],
        description: "",
      },
      formDataRules: {
        templateCode: [
          {
            required: true,
            trigger: "blur",
            validator: this.Helper.validateFunction,
          },
        ],
        templateName: [
          {
            required: true,
            trigger: "blur",
            validator: this.Helper.validateFunction,
          },
        ],
        // sampleCategoryName: [
        //   {
        //     required: true,
        //     trigger: "blur",
        //     validator: this.Helper.validateFunction
        //   }
        // ]
      },
      initErrorMsg: {
        templateCode: "",
        templateName: "",
        industry: "",
        sampleCategoryName: "",
        detectionItemName: "",
        description: "",
      },
      errorMsg: {
        templateCode: "",
        templateName: "",
        industry: "",
        sampleCategoryName: "",
        detectionItemName: "",
        description: "",
      },
    };
  },
  watch: {
    dialogFormVisible(val) {
      this.innerDialogFormVisible = val;
      val && this.init();
    },
    innerDialogFormVisible(val) {
      this.$emit("update:dialogFormVisible", val);
    },
    // "formData.sampleCategoryName": {
    //   handler(newVal, oldVal) {
    //     if (!Array.isArray(newVal) && newVal !== "") {
    //       this.formData.sampleCategoryName = newVal.split(",");
    //       return;
    //     }
    //     if (newVal.length > oldVal.length) {
    //       this.formData.experimentSampleCategorys.push({
    //         id: new Date().getTime() + "",
    //         name: newVal[newVal.length - 1],
    //         check: false,
    //       });
    //     }
    //   },
    //   immediate: false,
    // },
    "formData.detectionItemName": {
      handler(newVal, oldVal) {
        if (!Array.isArray(newVal) && newVal !== "") {
          this.formData.detectionItemName = newVal.split(",");
          return;
        }
        if (newVal.length > oldVal.length) {
          this.formData.experimentDetectionItems.push({
            id: new Date().getTime() + "",
            name: newVal[newVal.length - 1],
            check: false,
          });
        }
      },
      immediate: false,
    },
  },
  methods: {
    // 关闭选择检测项目弹框
    detectionItemClose(data) {
      this.tableDetectionItem = [];
      this.tableDetectionItemAndSubentry = [];
      for (let i = 0; i < data.length; i++) {
        for (let o = 0; o < data[i].detectionItemData.length; o++) {
          var data1 = data[i].detectionItemData[o];
          this.tableDetectionItem.push({
            id: data1.sysBusinessDetectionItemId,
            sysBusinessDetectionItemId: data1.sysBusinessDetectionItemId
              ? data1.sysBusinessDetectionItemId
              : data1.id, // 选择检测项目反显使用
            detectionItemId: data1.sysBusinessDetectionItemId
              ? data1.sysBusinessDetectionItemId
              : data1.id, // 选择检测项目反显使用
            sysBusinessSampleCategoryId: data[i].sysBusinessSampleCategoryId,
            sampleTypeName: data[i].sampleTypeName, // 选择检测项目反显使用
            sampleCategoryName: data[i].sampleTypeName,
            methodStandard: data1.methodStandard, // 选择检测项目反显使用
            name: data1.detectionItemName,
            detectionItemName: data1.detectionItemName,
            sysBusinessDetectionItemSonName:
              data1.sysBusinessDetectionItemSonName,
            sysBusinessDetectionItemSonList:
              data1.sysBusinessDetectionItemSonList,
            detectionItemParentId: data1.parentId,
            parentId: data1.parentId,
            dataPositioning: "",
            iconStyle: "font-size: 25px;cursor: pointer",
          });
          if (data1.sysBusinessDetectionItemSonList != null) {
            for (
              let p = 0;
              p < data1.sysBusinessDetectionItemSonList.length;
              p++
            ) {
              var data2 = data1.sysBusinessDetectionItemSonList[p];
              this.tableDetectionItemAndSubentry.push({
                id: data2.sysBusinessDetectionItemId,
                sysBusinessDetectionItemId: data2.sysBusinessDetectionItemId
                  ? data2.sysBusinessDetectionItemId
                  : data2.id,
                detectionItemId: data1.sysBusinessDetectionItemId
                  ? data1.sysBusinessDetectionItemId
                  : data1.id, // 选择检测项目反显使用
                sysBusinessSampleCategoryId:
                  data[i].sysBusinessSampleCategoryId,
                methodStandard: data1.methodStandard,
                sampleCategoryName: data[i].sampleTypeName,
                sampleTypeName: data[i].sampleTypeName,
                name: data2.detectionItemName,
                detectionItemName: data2.detectionItemName,
                detectionItemParentId: data2.parentId,
                parentId: data2.parentId,
                dataPositioning: "",
                iconStyle: "font-size: 25px;cursor: pointer",
              });
            }
          }
        }
      }
      var detectionData = this.tableDetectionItem.concat(
        this.tableDetectionItemAndSubentry
      );
      if (
        this.formData.tableDetectionItemAll !== undefined &&
        this.formData.tableDetectionItemAll !== null
      ) {
        for (let i = 0; i < detectionData.length; i++) {
          var datection = this.formData.tableDetectionItemAll.find(
            (x) =>
              x.sysBusinessDetectionItemId ===
              detectionData[i].sysBusinessDetectionItemId
          );
          if (datection !== undefined && datection !== null) {
            detectionData[i].resultColumn = datection.resultColumn;
            detectionData[i].resultRow = datection.resultRow;
            detectionData[i].tableId = datection.tableId;
            detectionData[i].tableName = datection.tableName;
            detectionData[i].c = datection.resultColumn;
            detectionData[i].r = datection.resultRow;
            detectionData[i].title = datection.tableName;
            detectionData[i].dataPositioning = datection.dataPositioning;
          }
        }
      }
      this.formData.tableDetectionItemAll = detectionData;
    },
    // 选择检测项目
    choiceDetectionItem() {
      if (
        this.formData.tableDetectionItemAll !== undefined &&
        this.formData.tableDetectionItemAll.length > 0 &&
        this.formData.tableDetectionItemAll !== null
      ) {
        var data = this.formData.tableDetectionItemAll.filter(
          (x) => x.detectionItemParentId === "0"
        );

        var sampleCategoryIdList = this.uniqueObjects(
          data,
          "sysBusinessSampleCategoryId"
        );
        var sampleDeteciontItemData = [];
        for (let o = 0; o < sampleCategoryIdList.length; o++) {
          var detectionData = [];
          for (let i = 0; i < data.length; i++) {
            if (
              data[i].sysBusinessSampleCategoryId ===
              sampleCategoryIdList[o].sysBusinessSampleCategoryId
            ) {
              detectionData.push(JSON.parse(JSON.stringify(data[i])));
              var sonDatection = this.formData.tableDetectionItemAll.filter(
                (x) =>
                  x.detectionItemParentId === data[i].sysBusinessDetectionItemId
              );

              if (sonDatection !== undefined && sonDatection !== null) {
                detectionData[
                  detectionData.length - 1
                ].sysBusinessDetectionItemSonList = sonDatection;
                detectionData[
                  detectionData.length - 1
                ].sysBusinessDetectionItemSonName = sonDatection
                  .map((item) => item.name)
                  .join(",");
              }
            }
          }
          sampleDeteciontItemData.push({
            detectionItemData: JSON.parse(JSON.stringify(detectionData)),
            sysBusinessSampleCategoryId:
              sampleCategoryIdList[o].sysBusinessSampleCategoryId,
            sampleTypeName: sampleCategoryIdList[o].sampleCategoryName, // 选择检测项目反显使用
          });
        }
        this.$refs.ChoiceDetectionItemDialog.sampleDeteciontItemData =
          sampleDeteciontItemData;
        // 选择的检测项目表赋值检测项目
        this.$refs.ChoiceDetectionItemDialog.selectedTableData = JSON.parse(
          JSON.stringify(data)
        );
      }

      this.dialogDetectionItem = true;
    },

    // 自定义方法进行去重
    uniqueObjects(arr, key) {
      return Object.values(
        arr.reduce((acc, item) => {
          acc[item[key]] = item;
          return acc;
        }, {})
      );
    },

    init() {
      if (!this.editId) {
        this.tableDetectionItem = [];
        this.formData = {
          templateCode: "",
          templateName: "",
          industry: "",
          // sampleCategoryName: "",
          templateContentDto: "",
          experimentSampleCategorys: [],
          detectionItemName: "",
          experimentDetectionItems: [],
          description: "",
          tableDetectionItemAll: [],
        };
        return;
      }
      getSingleList({ Id: this.editId }).then((res) => {
        const { data } = res;
        this.formData.tableDetectionItemAll = [];
        this.tableDetectionItem = [];

        for (const k in this.formData) {
          this.formData[k] = data[k];
        }
        if (
          data.experimentDetectionItemDtos !== undefined &&
          data.experimentDetectionItemDtos !== null &&
          data.experimentDetectionItemDtos.length !== 0
        ) {
          this.formData.tableDetectionItemAll =
            data.experimentDetectionItemDtos;
          for (let i = 0; i < this.formData.tableDetectionItemAll.length; i++) {
            this.formData.tableDetectionItemAll[i].iconStyle =
              "font-size: 25px;cursor: pointer";
            this.formData.tableDetectionItemAll[i].detectionItemName =
              this.formData.tableDetectionItemAll[i].name; // 选择检测项目反显使用
          }
          var detectionData = data.experimentDetectionItemDtos.filter(
            (item) => item.detectionItemParentId === "0"
          );
          var subitem = data.experimentDetectionItemDtos.filter(
            (item) => item.detectionItemParentId !== "0"
          );
          for (let i = 0; i < detectionData.length; i++) {
            var subitemData = [];
            subitemData = subitem.filter(
              (x) =>
                x.detectionItemParentId ===
                detectionData[i].sysBusinessDetectionItemId
            );
            for (let o = 0; o < subitemData.length; o++) {
              subitemData[o].parentId = subitemData[o].detectionItemParentId;
            }
            const detectionItemNameList = subitemData.map((item) => item.name);
            this.tableDetectionItem.push({
              sysBusinessDetectionItemId:
                detectionData[i].sysBusinessDetectionItemId,
              name: detectionData[i].name,
              detectionItemParentId: detectionData[i].detectionItemParentId,
              parentId: detectionData[i].detectionItemParentId,
              iconStyle: "font-size: 25px;cursor: pointer",
              id: detectionData[i].sysBusinessDetectionItemId,
              methodStandard: detectionData[i].methodStandard,
              sampleCategoryName: detectionData[i].sampleCategoryName,
              sampleTypeName: detectionData[i].sampleCategoryName,
              sysBusinessSampleCategoryId:
                detectionData[i].sysBusinessSampleCategoryId,
              sysBusinessDetectionItemSonList: subitemData,
              sysBusinessDetectionItemSonName: detectionItemNameList.join(","),
            });
          }
        }

        this.formData.id = this.editId;
      });
    },
    cancel() {
      this.innerDialogFormVisible = false;
    },
    nextStep() {
      this.onSubmit(true);
    },
    closeDialog(type) {
      // type上层页面传递
      this.$parent.getList();
      if (type === "save") return;
      this.cancel();
    },
    // changeSampleCategoryName() {
    //   this.formData.experimentSampleCategorys =
    //     this.formData.experimentSampleCategorys.filter((option) =>
    //       this.formData.sampleCategoryName.some((item) => item === option.name)
    //     );
    // },
    changeDetectionItemName() {
      this.formData.experimentDetectionItems =
        this.formData.experimentDetectionItems.filter((option) =>
          this.formData.detectionItemName.some((item) => item === option.name)
        );
    },
    onSubmit: _.throttle(function (next) {
      this.$refs.formData.validate((valid) => {
        if (valid) {
          this.errorMsg = this.Helper.deepCopy(this.initErrorMsg);
          if (next === true) {
            this.$refs.ExperimentTemplateEditForm.formData = deepClone(
              this.formData
            );

            this.dialogFormVisible2 = true;
            return;
          }
          this.formData.detectionItemName = [];
          if (
            this.formData.tableDetectionItemAll !== undefined &&
            this.formData.tableDetectionItemAll !== null &&
            this.formData.tableDetectionItemAll.length !== 0
          ) {
            this.formData.tableDetectionItemAll.forEach((element) => {
              if (element.parentId === "0") {
                this.formData.detectionItemName.push(element.detectionItemName);
                this.formData.experimentDetectionItems.push({
                  check: false,
                  id: element.id,
                  name: element.detectionItemName,
                });
              }
            });
          }
          this.loading = true;
          if (this.editId === "") {
            create(this.formData)
              .then((res) => {
                if (res.code === 200) {
                  this.closeDialog();
                } else {
                  this.showValidateMsgCheck(res);
                }
                this.loading = false;
              })
              .catch(() => {
                this.loading = false;
              });
          } else {
            // 前端同步模板左侧数据
            this.formData.templateContentDto &&
              this.formData.templateContentDto.leftData.forEach((x) => {
                x.code === "templateCode" &&
                  (x.value = this.formData.templateCode);
                // x.code === "sampleCategoryName" &&
                //   (x.data = this.formData.experimentSampleCategorys);
              });
            this.formData.id = this.editId;
            update(this.formData)
              .then((res) => {
                if (res.code === 200) {
                  this.closeDialog();
                } else {
                  this.showValidateMsgCheck(res);
                }
                this.loading = false;
              })
              .catch(() => {
                this.loading = false;
              });
          }
        } else {
          return false;
        }
      });
    }, 2000),
    getTemplate(val) {
      this.formData.templateContentDto = val.templateContentDto;
      this.formData.id = val.id;
    },
    showValidateMsgCheck(res) {
      if (res.msg) {
        this.Helper.showValidateMsg("templateCode", this.errorMsg, res.msg);
        this.Helper.showValidateMsg("templateName", this.errorMsg, res.msg);
        // this.Helper.showValidateMsg(
        //   "sampleCategoryName",
        //   this.errorMsg,
        //   res.msg
        // );
      }
    },
  },
};
</script>

<style lang="scss" scoped>
::v-deep .el-form-item.readonly {
  .el-form-item__content {
    .el-select__tags {
      .el-tag__close {
        display: none;
      }
    }
  }
}
::v-deep .el-dialog__footer {
  padding: 16px !important;

  .el-button {
    width: 70px;
    & + .el-button {
      margin-left: 30px !important;
    }
  }
}
</style>
